<?php
include 'theme_options.php';

register_nav_menus(
  array(
	 'headernav' => __( '顶部主导航', 'wasz' ),
	 'footernav' => __( '底部导航', 'wasz' )
  )
);
   
/*** Images ***/
add_theme_support('post-thumbnails');
update_option('thumbnail_size_w', 570);
update_option('large_size_w', 800);

//thumbnails
set_post_thumbnail_size( 120, 80 ,true );
function don_the_thumbnail() {
global $post;
// 判断该文章是否设置的缩略图，如果有则直接显示
if ( has_post_thumbnail() ) {
echo '<a href="'.get_permalink().'" class="thumb">';
the_post_thumbnail();
echo '</a>';
} else { //如果文章没有设置缩略图，则查找文章内是否包含图片
$content = $post->post_content;
preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
$n = count($strResult[1]);
if($n > 0){ // 如果文章内包含有图片，就用第一张图片做为缩略图
echo '<a href="'.get_permalink().'" class="thumb"><img src="'.$strResult[1][0].'" /></a>';
}
}
}

//今天更新的文章篇数
function get_today_posts_count($type = 'post', $date = ''){
    global $wpdb;

    $count = wp_cache_get($type, 'today_counts');
    if ( false !== $count )
        return $count;

    $gt = preg_match('(\d{4}-\d{2}-\d{2})', $date) > 0?$date:date_i18n('Y-m-d');
    list($year, $month, $day) = preg_split('[-]', $gt);
    $time = mktime(0, 0, 0, $month, $day, $year) + 60 * 60 * 24;
    $lt = date_i18n('Y-m-d', $time);

    $query = "
        SELECT
            COUNT(ID)
        FROM
            {$wpdb->posts} p
        WHERE
            p.post_status = 'publish'
        AND p.post_type = %s
        AND p.post_date > %s
        AND p.post_date < %s
    ";
    $count = $wpdb->get_var($wpdb->prepare($query, $type, $gt, $lt));

    wp_cache_set($type, $count, 'today_counts');
    return $count;
}

// 获得热评文章
function simple_get_most_viewed($posts_num=10, $days=30){  
    global $wpdb;  
    $sql = "SELECT `ID` , `post_title` , `comment_count` FROM $wpdb->posts WHERE `post_type` = 'post' AND `post_status` = 'publish' AND TO_DAYS( now( ) ) - TO_DAYS( `post_date` ) < $days ORDER BY `comment_count` DESC LIMIT 0 , $posts_num ";
  
    $posts = $wpdb->get_results($sql);  
    $output = "";  
    foreach ($posts as $post){  
        $output .= "\n<li><a href= \"".get_permalink($post->ID)."\" rel=\"bookmark\" title=\"".$post->post_title."\" >".$post->post_title."</a></li>";  
    }  
    echo $output;  
}

/*解决截取汉字乱码*/
function cut_str($sourcestr,$cutlength)
{
$returnstr="";
$i=0;
$n=0;
$str_length=strlen($sourcestr);//字符串的字节数
while (($n<$cutlength) and ($i<=$str_length))
{
$temp_str=substr($sourcestr,$i,1);
$ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码
if ($ascnum>=224)//如果ASCII位高与224，
{
$returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
$i=$i+3;//实际Byte计为3
$n++;//字串长度计1
}
elseif ($ascnum>=192) //如果ASCII位高与192，
{
$returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
$i=$i+2;//实际Byte计为2
$n++;//字串长度计1
}
elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
{
$returnstr=$returnstr.substr($sourcestr,$i,1);
$i=$i+1;//实际的Byte数仍计1个
$n++;//但考虑整体美观，大写字母计成一个高位字符
}
else//其他情况下，包括小写字母和半角标点符号，
{
$returnstr=$returnstr.substr($sourcestr,$i,1);
$i=$i+1;//实际的Byte数计1个
$n=$n+0.5;//小写字母和半角标点等与半个高位字符宽…
}
}
if ($str_length>$cutlength){
$returnstr = $returnstr . "…";//超过长度时在尾处加上省略号
}
return $returnstr;
}

/*PAGINATION*/
function don_pagination($query_string){
	global $posts_per_page, $paged;
	$my_query = new WP_Query($query_string ."&posts_per_page=-1");
	$total_posts = $my_query->post_count;
	if(empty($paged))$paged = 1;
	$prev = $paged - 1;
	$next = $paged + 1;
	$range = 5; // only edit this if you want to show more page-links
	$showitems = ($range * 2)+1;
	
	$pages = ceil($total_posts/$posts_per_page);
	if(1 != $pages){
	echo "<div class='pagination'>";
	echo ($paged > 2 && $paged+$range+1 > $pages && $showitems < $pages)? "<a href='".get_pagenum_link(1)."'>最前</a>":"";
	echo ($paged > 1 && $showitems < $pages)? "<a href='".get_pagenum_link($prev)."'>上一页</a>":"";
	
	for ($i=1; $i <= $pages; $i++){
	if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems )){
	echo ($paged == $i)? "<span class='current'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='inactive' >".$i."</a>";
	}
}

echo ($paged < $pages && $showitems < $pages) ? "<a href='".get_pagenum_link($next)."'>下一页</a>" :"";
echo ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) ? "<a href='".get_pagenum_link($pages)."'>最后</a>":"";
echo "</div>\n";
}
}

//面包屑导航
function don_breadcrumbs() {
 
  $delimiter = '&raquo;';
  $name = '首页'; //text for the 'Home' link

  if ( !is_home() && !is_front_page() || is_paged() ) {
 
    global $post;
    $home = get_bloginfo('url');
    echo '<a href="' . $home . '">' . $name . '</a> ' . $delimiter . ' ';
 
    if ( is_category() ) {
      global $wp_query;
      $cat_obj = $wp_query->get_queried_object();
      $thisCat = $cat_obj->term_id;
      $thisCat = get_category($thisCat);
      $parentCat = get_category($thisCat->parent);
      if ($thisCat->parent != 0) echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
      single_cat_title();
 
    } elseif ( is_day() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
      echo $currentBefore . get_the_time('d') . $currentAfter;
 
    } elseif ( is_month() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo $currentBefore . get_the_time('F') . $currentAfter;
 
    } elseif ( is_year() ) {
      echo $currentBefore . get_the_time('Y') . $currentAfter;
 
    } elseif ( is_single() ) {
      $cat = get_the_category(); $cat = $cat[0];
      echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
      echo $currentBefore;
      the_title();
      echo $currentAfter;
 
    } elseif ( is_page() && !$post->post_parent ) {
      echo $currentBefore;
      the_title();
      echo $currentAfter;
 
    } elseif ( is_page() && $post->post_parent ) {
      $parent_id  = $post->post_parent;
      $breadcrumbs = array();
      while ($parent_id) {
        $page = get_page($parent_id);
        $breadcrumbs[] = '<a href="' . get_permalink($page-ID) . '">' . get_the_title($page->ID) . '</a>';
        $parent_id  = $page->post_parent;
      }
      $breadcrumbs = array_reverse($breadcrumbs);
      foreach ($breadcrumbs as $crumb) echo $crumb . ' ' . $delimiter . ' ';
      echo $currentBefore;
      the_title();
      echo $currentAfter;
 
    } elseif ( is_search() ) {
      echo $currentBefore . '搜索 &#39;' . get_search_query() . '&#39;' . $currentAfter;
 
    } elseif ( is_tag() ) {
      echo $currentBefore . '标签 &#39;';
      single_tag_title();
      echo '&#39;' . $currentAfter;
 
    } elseif ( is_author() ) {
       global $author;
      $userdata = get_userdata($author);
      echo $currentBefore . '归档 ' . $userdata->display_name . $currentAfter;
 
    } elseif ( is_404() ) {
      echo $currentBefore . '404错误' . $currentAfter;
    }
 
    if ( get_query_var('paged') ) {
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
      echo __('第') . get_query_var('paged') . ('页');
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
    }
  }
}

//自定义评论列表
function custom_comments($comment, $args, $depth) {
	$GLOBALS['comment'] = $comment;
	$GLOBALS['comment_depth'] = $depth;
?>
<li <?php comment_class(); ?> id="comment-<?php comment_ID() ?>">
	<div class="intro fixed">
    	<div class="introimg"><?php echo get_avatar($comment, 50); ?></div>
		<div class="nick"><?php printf(__('<cite>%s</cite>'), get_comment_author_link()) ?>：</div>
		<?php if ($comment->comment_approved == '0') : ?>
		<p class="tip">请稍候，你的回应正在等待审核哦！</p>
		<?php endif; ?>
		<div class="txt"><?php comment_text() ?></div>
		<div class="cmreply">
			<?php
			if((get_option('thread_comments')) && ($args['type'] == 'all' || get_comment_type() == 'comment')) :
			$max_depth = get_option('thread_comments_depth');
			echo comment_reply_link(array(
			'reply_text' => __('回复'),
			'login_text' => __('请登录后回复'),
			'depth' => $depth,
			'max_depth' => $max_depth,
			'before' => '<span class="reply">',
			'after' => '</span>'
			));
			endif;
			?>
		</div>
        <div class="date"><?php comment_date('Y-m-d') ?> <?php comment_time('H:i') ?></div>
	</div>
<?php
}
function custom_comments_end() {
	echo '</li>';
}

/* comment_mail_notify v1.0 by willin kan. (有勾选项，由游客决定) */
function comment_mail_notify($comment_id) {
  $admin_notify = '0'; // admin 要不要回复通知 ( '1'=要 ; '0'=不要 )
  $admin_email = get_bloginfo ('admin_email'); // $admin_email 可改为你指定的 e-mail.
  $comment = get_comment($comment_id);
  $comment_author_email = trim($comment->comment_author_email);
  $parent_id = $comment->comment_parent ? $comment->comment_parent : '';
  global $wpdb;
  if ($wpdb->query("Describe {$wpdb->comments} comment_mail_notify") == '')
    $wpdb->query("ALTER TABLE {$wpdb->comments} ADD COLUMN comment_mail_notify TINYINT NOT NULL DEFAULT 0;");
  if (($comment_author_email != $admin_email && isset($_POST['comment_mail_notify'])) || ($comment_author_email == $admin_email && $admin_notify == '1'))
    $wpdb->query("UPDATE {$wpdb->comments} SET comment_mail_notify='1' WHERE comment_ID='$comment_id'");
  $notify = $parent_id ? get_comment($parent_id)->comment_mail_notify : '0';
  $spam_confirmed = $comment->comment_approved;
  if ($parent_id != '' && $spam_confirmed != 'spam' && $notify == '1') {
    $wp_email = 'no-reply@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); // e-mail 发出点, no-reply可改为可用的 e-mail.
    $to = trim(get_comment($parent_id)->comment_author_email);
    $subject = '您在 [' . get_option("blogname") . '] 的留言有了回应';
    $message = '
    <div style="background-color:#eef2fa; border:1px solid #d8e3e8; color:#111; padding:0 15px; -moz-border-radius:5px; -webkit-border-radius:5px; -khtml-border-radius:5px;">
      <p>' . trim(get_comment($parent_id)->comment_author) . ', 您好！</p>
      <p>您曾在《' . get_the_title($comment->comment_post_ID) . '》的留言：<br />'
       . trim(get_comment($parent_id)->comment_content) . '</p>
      <p>' . trim($comment->comment_author) . ' 给您的回应：<br />'
       . trim($comment->comment_content) . '<br /></p>
      <p>您可以点击 <a href="' . htmlspecialchars(get_comment_link($parent_id)) . '">查看完整内容并进行反击！</a></p>
      <p>欢迎再次光临 <a href="' . get_option('home') . '">' . get_option('blogname') . '</a></p>
      <p>(此邮件由系统自动发出，请勿回复.)</p>
    </div>';
    $from = "From: \"" . get_option('blogname') . "\" <$wp_email>";
    $headers = "$from\nContent-Type: text/html; charset=" . get_option('blog_charset') . "\n";
    wp_mail( $to, $subject, $message, $headers );
    //echo 'mail to ', $to, '<br/> ' , $subject, $message; // for testing
  }
}
add_action('comment_post', 'comment_mail_notify');

/* 自动勾选 */
function add_checkbox() {
  echo '<input type="checkbox" name="comment_mail_notify" id="comment_mail_notify" value="comment_mail_notify" checked="checked" style="margin-left:20px;" /><label for="comment_mail_notify">有人回复时邮件通知我</label>';
}
add_action('comment_form', 'add_checkbox');

function commentdata_fix($commentdata) {
    if ( $commentdata['comment_author_url'] == 'WWW') {
        $commentdata['comment_author_url'] = '';
    }
    if ($commentdata['comment_content'] == 'Write your comment') {
        $commentdata['comment_content'] = '';
    }
    return $commentdata;
}
add_filter('preprocess_comment','commentdata_fix');

function getTinyUrl($url) {
    $tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
    return $tinyurl;
}

function get_blogurl() {
    if (get_option('show_on_front') == 'page' && get_option('page_for_posts') != 0) {
        $blogpage = get_page(get_option('page_for_posts'));
        echo $blogpage -> guid;
    } else {
        echo get_option('home');
    }
}

function n_posts_link_attributes(){
	return 'class="nextpostslink"';
}
function p_posts_link_attributes(){
	return 'class="previouspostslink"';
}

//根据别名获取链接

function geturl($slug, $type="page"){ //slug

    global $wpdb;

    if ($type == "page") { //传过来的是页面的别名

       $url_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$slug."'");
echo get_permalink($url_id); //输出页面链接

    }else{ //传过来的是分类的别名

       $url_id = $wpdb->get_var("SELECT term_id FROM $wpdb->terms WHERE slug = '".$slug."'");
echo get_category_link($url_id); //输出分类链接

    }
}

add_filter('next_posts_link_attributes', 'n_posts_link_attributes');
add_filter('previous_posts_link_attributes', 'p_posts_link_attributes');

//邮件收发
add_action ( 'wp_enqueue_scripts', 'wpjam_cf7_enqueue_scripts', 99 );

function wpjam_cf7_enqueue_scripts(){

wp_dequeue_script('contact-form-7');

if(is_page('services')){

$in_footer = true;

if ( 'header' === WPCF7_LOAD_JS )

$in_footer = false;

wp_enqueue_script( 'contact-form-7',

wpcf7_plugin_url( 'includes/js/scripts.js' ),

array( 'jquery', 'jquery-form' ), WPCF7_VERSION, $in_footer );

}

}

add_action( 'wp_enqueue_scripts', 'wpjam_cf7_enqueue_styles', 99 );

function wpjam_cf7_enqueue_styles() {

wp_dequeue_style('contact-form-7');

if(is_page('services')){

wp_enqueue_style( 'contact-form-7',

wpcf7_plugin_url( 'includes/css/styles.css' ),

array(), WPCF7_VERSION, 'all' );

}

}

?>